package com.gin.no_gay_alliance.manager;

import android.util.Log;

import androidx.annotation.NonNull;

import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.response.body.nuke.LoadTopicBody;
import com.gin.nga.response.field.TopicInfoSimple;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Bundle;
import com.gin.no_gay_alliance.callback.Callback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;

/**
 * 用户最近主题管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/12 11:34
 **/
public class UserRecentTopicManager {
    public static final String TAG = UserRecentTopicManager.class.getSimpleName();
    /**
     * 缓存对象
     */
    private final HashMap<Long, Bundle<List<TopicInfoSimple>>> cache = new HashMap<>();

    public UserRecentTopicManager() {
        Log.d(TAG, "创建:用户最近主题管理器");
    }

    /**
     * 执行请求
     *
     * @param ignoreCache 是否忽略缓存
     * @param userId      用户id
     * @param callback    回调
     */
    public void request(boolean ignoreCache, long userId, @NonNull Callback<List<TopicInfoSimple>> callback) {
        // 客户端
        NgaClient client = MyApplication.getClient();

        // 检查缓存
        if (Bundle.checkCache(ignoreCache, cache, userId, callback)) {
            return;
        }
        callback.beforeRequest();
        // 执行请求
        NukeApi.loadRecentTopic(client, userId).async(new JsonCallback<LoadTopicBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onFailure(call, e);
            }

            @Override
            public void onSuccess(LoadTopicBody body) {
                List<TopicInfoSimple> data = new ArrayList<>(body.getData().values());
                Bundle<List<TopicInfoSimple>> bundle = new Bundle<>(data, 30, TimeUnit.MINUTES);
                cache.put(userId, bundle);
                callback.onSuccess(data);
            }

            @Override
            public void handleException(NgaException e) {
                callback.handleException(e);
            }
        });
    }
}
